package com.uchedao.seller.ui.car.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.uchedao.seller.R;
import com.uchedao.seller.module.Detection;
import com.uchedao.seller.config.GlobalInfo;
import com.uchedao.seller.widget.dialog_for_ios.ZAlertDialog;
import com.uchedao.seller.widget.stickylistheaders.StickyListHeadersAdapter;

import java.util.ArrayList;

public class DetectionAdapter extends BaseAdapter implements
        StickyListHeadersAdapter {
    /**
     * 单选监听接口
     *
     * @author "叶晋"
     */
    public interface DetectionSingleAdapterListener {
        /**
         * 单值结果
         *
         * @param position
         * @param value
         */
        public void onSingleResult(int position, int value);

    }

    /**
     * 多选监听接口
     *
     * @author "叶晋"
     */
    public interface DetectionMultipleAdapterListener {
        /**
         * 多值结果
         *
         * @param position
         * @param values
         */
        public void onMultipleResult(int position, ArrayList<Integer> values);
    }

    public ArrayList<Detection> array;

    private LayoutInflater inflater;

    private Context mContext;

    // 当前索引
    private int index;

    private DetectionSingleAdapterListener singleListener;

    private DetectionMultipleAdapterListener multipleListener;

    private int resultTvWidth;

    // 多选项的值
    private boolean[] checkedItems;

    public DetectionAdapter(Context context, ArrayList<Detection> list,
                            DetectionSingleAdapterListener adapterListener) {
        inflater = LayoutInflater.from(context);
        array = list;
        mContext = context;
        singleListener = adapterListener;

    }

    public DetectionAdapter(Context context, ArrayList<Detection> list,
                            DetectionMultipleAdapterListener adapterListener) {
        inflater = LayoutInflater.from(context);
        array = list;
        mContext = context;
        multipleListener = adapterListener;

    }

    @Override
    public int getCount() {
        if (array == null)
            return 0;
        return array.size();
    }

    @Override
    public Object getItem(int position) {
        if (array == null)
            return 0;
        return array.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    class ViewHolder {
        TextView text;
        LinearLayout inputLayout;
        ImageView star;
        EditText edit;
        TextView unit;
        TextView result;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.item_detection, null);
            convertView.setTag(viewHolder);
            viewHolder.text = (TextView) convertView
                    .findViewById(R.id.subject_tv);
            viewHolder.inputLayout = (LinearLayout) convertView
                    .findViewById(R.id.input_result_layout);
            viewHolder.star = (ImageView) convertView
                    .findViewById(R.id.input_tip_iv);
            viewHolder.edit = (EditText) convertView
                    .findViewById(R.id.input_result_et);
            viewHolder.unit = (TextView) convertView.findViewById(R.id.unit_tv);
            viewHolder.result = (TextView) convertView
                    .findViewById(R.id.detection_result_tv);
            viewHolder.result.setMinWidth(resultTvWidth);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        Detection detection = array.get(position);

        // // 输入框
        // if ((detection.getValueType() & Detection.TYPE_INPUT) != 0) {
        // viewHolder.inputLayout.setVisibility(View.VISIBLE);
        // viewHolder.unit.setText(detection.getKey());
        // viewHolder.edit.setTag(detection);
        // viewHolder.edit.setText(detection.getStrValue());
        //
        // } else {
        // viewHolder.inputLayout.setVisibility(View.GONE);
        // }

        viewHolder.text.setText(detection.getText());

        viewHolder.result.setTag(position);
        // 设置值
        setResult(detection, viewHolder.result);

        return convertView;
    }

    /**
     * 单选监听
     */
    private OnClickListener singleChoiceListener = new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Detection detection = array.get(index);

            detection.setValue(which);
            notifyDataSetChanged();
            if (singleListener != null)
                singleListener.onSingleResult(index, which);
        }
    };

    /**
     * 显示单选对话框
     *
     * @param listener
     */
    private void showAlertSingleChoiceDialog(Detection detection,
                                             OnClickListener listener) {
        AlertDialog alert = new ZAlertDialog.Builder(mContext)
                .setTitle(detection.getText())
                .setItems(detection.getResId(), listener).create();
        alert.show();
    }

    /**
     * 只能单选的多选值
     *
     * @param value
     * @return
     */
    private boolean multipleValueOnlyRadio(String value) {
        return "正常".equals(value) || "无".equals(value);
    }

    /**
     * 多选监听
     */
    private DialogInterface.OnMultiChoiceClickListener multipleChoiceListener = new DialogInterface.OnMultiChoiceClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {

            Detection detection = array.get(index);
            ListView listView = ((AlertDialog) dialog).getListView();

            // 取消选择
            if (!isChecked) {
                // 当选中的数量小于1时
                if (listView.getCheckedItemCount() == 0) {
                    listView.setItemChecked(which, true);
                    checkedItems[which] = true;
                    Toast.makeText(mContext, R.string.at_least_choice_one,
                            Toast.LENGTH_LONG).show();
                }
                return;

            }

            String[] values = GlobalInfo.resources.getStringArray(detection
                    .getResId());

            // 若该选项只能单选
            if (multipleValueOnlyRadio(values[which])) {
                // 除此项外，其余值取消选择
                for (int i = 0; i < values.length; i++) {
                    listView.setItemChecked(i, i == which);
                    checkedItems[i] = (i == which);
                }

                // 若该选项能多选
            } else {

                for (int i = 0; i < values.length; i++) {
                    // 其余单选项取消选择
                    if (multipleValueOnlyRadio(values[i])) {
                        listView.setItemChecked(i, false);
                        checkedItems[i] = false;
                    }
                }
            }
        }
    };

    /**
     * 显示多选对话框
     *
     * @param listener
     */
    private void showAlertMultipleChoiceDialog(Detection detection,
                                               DialogInterface.OnMultiChoiceClickListener listener) {
        ArrayList<Integer> ints = detection.getValues();
        int size = GlobalInfo.resources.getStringArray(detection.getResId()).length;
        checkedItems = new boolean[size];
        for (int i : ints)
            checkedItems[i] = true;

        OnClickListener okClickListener = new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Detection detection = array.get(index);

                ArrayList<Integer> ints = new ArrayList<Integer>();
                for (int i = 0; i < checkedItems.length; i++) {
                    if (checkedItems[i])
                        ints.add(i);
                }
                detection.setValues(ints);
                notifyDataSetChanged();

                if (multipleListener != null)
                    multipleListener.onMultipleResult(index, ints);

            }
        };
        new ZAlertDialog.Builder(mContext)
                .setTitle(detection.getText())
                .setMultiChoiceItems(detection.getResId(), checkedItems,
                        listener)
                .setPositiveButton(R.string.ok, okClickListener)
                .setNegativeButton(R.string.cancel, null).create().show();

    }

    /**
     * 值监听
     */
    private View.OnClickListener resultOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            index = (Integer) v.getTag();
            Detection detection = array.get(index);

            // 二选一
            if ((detection.getValueType() & Detection.TYPE_TWO_SELECT) != 0) {
                showAlertSingleChoiceDialog(detection, singleChoiceListener);
                // 三选一
            } else if ((detection.getValueType() & Detection.TYPE_THREE_SELECT) != 0) {
                showAlertSingleChoiceDialog(detection, singleChoiceListener);

                // 多选
            } else if ((detection.getValueType() & Detection.TYPE_MULTIPLE) != 0) {
                showAlertMultipleChoiceDialog(detection, multipleChoiceListener);
            }

        }
    };

    /**
     * 设置值
     *
     * @param tv
     */
    private void setResult(Detection detection, TextView tv) {
        // 二选一
        if ((detection.getValueType() & Detection.TYPE_TWO_SELECT) != 0) {
            String[] values = GlobalInfo.resources.getStringArray(detection.getResId());

            if(detection.getValue() >= 0)
                tv.setText(values[detection.getValue()]);

            // key有正确值时
            if (!TextUtils.isEmpty(detection.getKey())) {
                // 相同为正常
                if (detection.getKey().equals(values[detection.getValue()])) {
                    tv.setBackgroundResource(R.color.deep_green);
                    tv.setCompoundDrawablesWithIntrinsicBounds(
                            R.mipmap.ic_blue_yes, 0,
                            R.mipmap.ic_drop_arrow, 0);
                } else {
                    tv.setBackgroundResource(R.color.deep_red);
                    tv.setCompoundDrawablesWithIntrinsicBounds(
                            R.mipmap.ic_red_cross, 0,
                            R.mipmap.ic_drop_arrow, 0);
                }

            } else {

                if (detection.getValue() == 1) {// 正常
                    tv.setBackgroundResource(R.color.deep_green);
                    tv.setCompoundDrawablesWithIntrinsicBounds(
                            R.mipmap.ic_blue_yes, 0,
                            R.mipmap.ic_drop_arrow, 0);
                } else {
                    tv.setBackgroundResource(R.color.deep_red);
                    tv.setCompoundDrawablesWithIntrinsicBounds(
                            R.mipmap.ic_red_cross, 0,
                            R.mipmap.ic_drop_arrow, 0);
                }
            }

            // 三选一
        } else if ((detection.getValueType() & Detection.TYPE_THREE_SELECT) != 0) {
            String[] values = GlobalInfo.resources.getStringArray(detection.getResId());

            if(detection.getValue() >= 0)
                tv.setText(values[detection.getValue()]);

            if (detection.getValue() <= 0) {// 正常
                tv.setBackgroundResource(R.color.deep_green);
                tv.setCompoundDrawablesWithIntrinsicBounds(
                        R.mipmap.ic_blue_yes, 0,
                        R.mipmap.ic_drop_arrow, 0);
            } else {
                tv.setBackgroundResource(R.color.deep_red);
                tv.setCompoundDrawablesWithIntrinsicBounds(
                        R.mipmap.ic_red_cross, 0,
                        R.mipmap.ic_drop_arrow, 0);
            }

            // 多选
        } else if ((detection.getValueType() & Detection.TYPE_MULTIPLE) != 0) {
            String[] values = GlobalInfo.resources.getStringArray(detection.getResId());

            ArrayList<Integer> ints = detection.getValues();

            // 若为空值，默认为0
//            if (ints.size() == 0)
//                ints.add(0);

            String value = "";
            for (int i : ints) {
                if (TextUtils.isEmpty(value))
                    value = values[i];
                else
                    value += " " + values[i];
            }
            tv.setText(value);

            if (ints.size() <= 0 || multipleValueOnlyRadio(values[ints.get(0)])) {// 正常
                tv.setBackgroundResource(R.color.deep_green);
                tv.setCompoundDrawablesWithIntrinsicBounds(
                        R.mipmap.ic_blue_yes, 0,
                        R.mipmap.ic_drop_arrow, 0);
            } else {
                tv.setBackgroundResource(R.color.deep_red);
                tv.setCompoundDrawablesWithIntrinsicBounds(
                        R.mipmap.ic_red_cross, 0,
                        R.mipmap.ic_drop_arrow, 0);
            }

        }

        if (detection.isRequestFocus()) {
            tv.setOnClickListener(resultOnClickListener);
        }
    }

    class HeaderViewHolder {
        TextView header;
        TextView result;
    }

    @Override
    public View getHeaderView(int position, View convertView, ViewGroup parent) {
        HeaderViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new HeaderViewHolder();
            convertView = inflater.inflate(R.layout.item_detection_subject, null);
            convertView.setTag(viewHolder);
            viewHolder.header = (TextView) convertView
                    .findViewById(R.id.detection_subject_name_tv);
            viewHolder.result = (TextView) convertView
                    .findViewById(R.id.skeleton_subject_result_tv);
            viewHolder.result.setMinWidth(resultTvWidth);

        } else {
            viewHolder = (HeaderViewHolder) convertView.getTag();
        }
        Detection detection = array.get(position);
        viewHolder.header.setText(detection.getHeader());

        return convertView;
    }

    @Override
    public long getHeaderId(int position) {
        return array.get(position).getHeader().hashCode();
    }

    public void setResultTvWidth(int resultTvWidth) {
        this.resultTvWidth = resultTvWidth;
    }
}
